// pages/scrollviewrefresh6/scrollviewrefresh6.js
/*
  说明：在scrollviewrefresh5 demo的基础上，每个分类中的商品商户模拟从服务端获取
*/




var touchChange = false

Page({

  /**
   * 页面的初始数据
   */
  data: {
    categoryTree: null, //分类树
    selectedLevel1Index: 0,
    selectedLevel2Index: 0,
    //
    level1ScrollViewToView: '',
    level2ScrollViewToView: '',
    //
    goodsScrollViewToView: '',
    upperThreshold: -50,
    lowerThreshold: -50,
    hideBottomLoadNext: true,
    //
    swiperCategoryArray: null,
    currentSwiperIndex: 0,
    coverScrollViewShow: false,
    coverScrollViewItemList: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var categoryData = []
    //一级分类
    for (var i1 = 0; i1 < 16; i1++) {
      var level1ItemObj = {
        id: 'level1_' + i1,
        name: '一级' + i1,
      }

      if (i1 == 1 || i1 == 6) {
        
      }
      else {
        var level2Array = []
        //二级分类
        for (var i2 = 0; i2 < 4; i2++) {
          var level2ItemObj = {
            id: 'level1_' + i1 + '_level2_' + i2,
            name: '二级' + i2,
          }

          level2Array.push(level2ItemObj)
        }
        level1ItemObj.children = level2Array
      }

      categoryData.push(level1ItemObj)
    }

    this.setData({
      categoryTree: categoryData,
    })
    //console.log(JSON.stringify(categoryData))
    //
    this.fillSwiperCategoryArray()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 点击响应 - 一级分类项
   */
  tapLevel1Item: function (event) {
    var index = event.currentTarget.dataset.index
    if (index == this.data.selectedLevel1Index) {
      return
    }
    else {
      this.setData({
        selectedLevel1Index: index,
        selectedLevel2Index: 0,
      })

      this.fillSwiperCategoryArray()
      this.setData({
        level1ScrollViewToView: 'item' + this.data.selectedLevel1Index,
        level2ScrollViewToView: 'item' + this.data.selectedLevel2Index,
      })
      wx.vibrateShort()
    }
  },

  /**
   * 点击响应 - 二级分类项
   */
  tapLevel2Item: function (event) {
    var index = event.currentTarget.dataset.index
    if (index == this.data.selectedLevel2Index) {
      return
    }
    else {
      this.setData({
        selectedLevel2Index: index,
      })
      this.fillSwiperCategoryArray()
      this.setData({
        level2ScrollViewToView: 'item' + this.data.selectedLevel2Index,
      })
      wx.vibrateShort()
    }
  },

  /**
   * 响应事件
   */
  preventTouchMove: function (event) {
    return false
  },

  /*
    给分类项加上index索引
  */
  getCategoryObjWithIndexPath(categoryObj, level1Index, level2Index) {
    categoryObj.level1Index = level1Index
    categoryObj.level2Index = level2Index
    return categoryObj
  },

  findLastCategory: function () {
    if (this.data.selectedLevel1Index == 0) { //是第一个一级分类
      if (this.data.categoryTree[this.data.selectedLevel1Index].children) { //有二级分类
        if (this.data.selectedLevel2Index == 0) { //第一个二级分类
          return null
        }
        else {
          //取当前一级分类中二级分类的上一个
          return this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index].children[this.data.selectedLevel2Index - 1], this.data.selectedLevel1Index, this.data.selectedLevel2Index - 1)
        }
      }
      else { //无二级分类
        return null //没有上一个分类了
      }
    }
    else { //不是第一个一级分类
      if (this.data.categoryTree[this.data.selectedLevel1Index].children) { //有二级分类
        if (this.data.selectedLevel2Index == 0) { //第一个二级分类
          var lastLevel1 = this.data.categoryTree[this.data.selectedLevel1Index - 1]
          if (lastLevel1.children) { //有二级分类
            return this.getCategoryObjWithIndexPath(lastLevel1.children[lastLevel1.children.length - 1], this.data.selectedLevel1Index - 1, lastLevel1.children.length - 1)
          }
          else {
            return this.getCategoryObjWithIndexPath(lastLevel1, this.data.selectedLevel1Index - 1, -1) //-1表示无二级分类
          }
        }
        else {
          //取当前一级分类中二级分类的上一个
          return this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index].children[this.data.selectedLevel2Index - 1], this.data.selectedLevel1Index, this.data.selectedLevel2Index - 1)
        }
      }
      else { //无二级分类
        var lastLevel1 = this.data.categoryTree[this.data.selectedLevel1Index - 1]
        if (lastLevel1.children) { //有二级分类
          return this.getCategoryObjWithIndexPath(lastLevel1.children[lastLevel1.children.length - 1], this.data.selectedLevel1Index - 1, lastLevel1.children.length - 1)
        }
        else {
          return this.getCategoryObjWithIndexPath(lastLevel1, this.data.selectedLevel1Index - 1, -1) //-1表示无二级分类
        }
      }
    }
  },

  findNextCategory: function () {
    if (this.data.selectedLevel1Index == this.data.categoryTree.length - 1) { //是最后一个一级分类
      if (this.data.categoryTree[this.data.selectedLevel1Index].children) { //有二级分类
        if (this.data.selectedLevel2Index == this.data.categoryTree[this.data.selectedLevel1Index].children.length - 1) { //最后一个二级分类
          return null
        }
        else {
          //取当前一级分类中二级分类的下一个
          return this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index].children[this.data.selectedLevel2Index + 1], this.data.selectedLevel1Index, this.data.selectedLevel2Index + 1)
        }
      }
      else { //无二级分类
        return null //没有下一个分类了
      }
    }
    else { //不是最后一个一级分类
      if (this.data.categoryTree[this.data.selectedLevel1Index].children) { //有二级分类
        if (this.data.selectedLevel2Index == this.data.categoryTree[this.data.selectedLevel1Index].children.length - 1) { //最后一个二级分类
          var nextLevel1 = this.data.categoryTree[this.data.selectedLevel1Index + 1]
          if (nextLevel1.children) { //有二级分类
            return this.getCategoryObjWithIndexPath(nextLevel1.children[0], this.data.selectedLevel1Index + 1, 0)
          }
          else {
            return this.getCategoryObjWithIndexPath(nextLevel1, this.data.selectedLevel1Index + 1, -1) //-1表示无二级分类
          }
        }
        else {
          //取当前一级分类中二级分类的下一个
          return this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index].children[this.data.selectedLevel2Index + 1], this.data.selectedLevel1Index, this.data.selectedLevel2Index + 1)
        }
      }
      else { //无二级分类
        var nextLevel1 = this.data.categoryTree[this.data.selectedLevel1Index + 1]
        if (nextLevel1.children) { //有二级分类
          return this.getCategoryObjWithIndexPath(nextLevel1.children[0], this.data.selectedLevel1Index + 1, 0)
        }
        else {
          return this.getCategoryObjWithIndexPath(nextLevel1, this.data.selectedLevel1Index + 1, -1) //-1表示无二级分类
        }
      }
    }
  },


  fillSwiperCategoryArray() {
    if (this.data.selectedLevel1Index == 0) { //第一个一级分类
      var tempSwiperArray = []
      var tempSwiperIndex = 0
      if (this.data.categoryTree[this.data.selectedLevel1Index].children) { //有二级分类
        if (this.data.selectedLevel2Index == 0) { //第一个二级分类
          //取前两个元素
          var current = this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index].children[this.data.selectedLevel2Index], this.data.selectedLevel1Index, this.data.selectedLevel2Index)
          var next = this.findNextCategory()
          tempSwiperArray.push(current)
          if (next) {
            tempSwiperArray.push(next)
          }

          tempSwiperIndex = 0
        }
        else { //其他的二级分类
          //取三个元素
          var current = this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index].children[this.data.selectedLevel2Index], this.data.selectedLevel1Index, this.data.selectedLevel2Index)
          var next = this.findNextCategory()

          tempSwiperArray.push(this.findLastCategory())
          tempSwiperArray.push(current)
          if (next) {
            tempSwiperArray.push(next)
          }

          tempSwiperIndex = 1
        }
      }
      else { //无二级分类
        //取前两个元素
        var current = this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index], this.data.selectedLevel1Index, -1)
        tempSwiperArray.push(current)
        var next = this.findNextCategory()
        if (next) {
          tempSwiperArray.push(next)
        }

        tempSwiperIndex = 0
      }

      this.setData({
        swiperCategoryArray: tempSwiperArray,
      })
      this.setData({
        currentSwiperIndex: tempSwiperIndex,
      })
    }
    else if (this.data.selectedLevel1Index == this.data.categoryTree.length - 1) { //最后一个一级分类
      var tempSwiperArray = []
      var tempSwiperIndex = 0
      if (this.data.categoryTree[this.data.selectedLevel1Index].children) { //有二级分类
        if (this.data.selectedLevel2Index == this.data.categoryTree[this.data.selectedLevel1Index].children.length - 1) { //最后一个二级分类
          //取最后两个元素
          var current = this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index].children[this.data.selectedLevel2Index], this.data.selectedLevel1Index, this.data.selectedLevel2Index)
          tempSwiperArray.push(this.findLastCategory())
          tempSwiperArray.push(current)
          tempSwiperIndex = 1
        }
        else {
          //取三个元素
          var current = this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index].children[this.data.selectedLevel2Index], this.data.selectedLevel1Index, this.data.selectedLevel2Index)
          tempSwiperArray.push(this.findLastCategory())
          tempSwiperArray.push(current)
          tempSwiperArray.push(this.findNextCategory())
          tempSwiperIndex = 1
        }
      }
      else { //无二级分类
        //取最后两个元素
        var current = this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index], this.data.selectedLevel1Index, -1)
        tempSwiperArray.push(this.findLastCategory())
        tempSwiperArray.push(current)
        tempSwiperIndex = 1
      }


      this.setData({
        swiperCategoryArray: tempSwiperArray, //取最后两个元素
      })
      this.setData({
        currentSwiperIndex: tempSwiperIndex,
      })
    }
    else { //其它的一级分类
      //取三个元素，当前元素在中间
      var tempSwiperArray = []
      if (this.data.categoryTree[this.data.selectedLevel1Index].children) { //有二级分类
        var current = this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index].children[this.data.selectedLevel2Index], this.data.selectedLevel1Index, this.data.selectedLevel2Index)
        tempSwiperArray.push(this.findLastCategory())
        tempSwiperArray.push(current)
        tempSwiperArray.push(this.findNextCategory())
      }
      else { //无二级分类
        var current = this.getCategoryObjWithIndexPath(this.data.categoryTree[this.data.selectedLevel1Index], this.data.selectedLevel1Index, -1)
        tempSwiperArray.push(this.findLastCategory())
        tempSwiperArray.push(current)
        tempSwiperArray.push(this.findNextCategory())
      }


      this.setData({
        swiperCategoryArray: tempSwiperArray,
      })

      this.setData({
        currentSwiperIndex: 1,
      })
    }

    console.log(this.data.swiperCategoryArray)
    console.log("currentSwiperIndex: " + this.data.currentSwiperIndex)

    /***** 请求swiper中每个分类下的商品列表 ******/
    /********* 开始 *********/
    for (var i = 0; i < this.data.swiperCategoryArray.length; i++) {
      var ele = this.data.swiperCategoryArray[i]
      if (!ele.goodsList) {
        console.log("------------该分类还未获取商品列表----------")
        this.requestGoodsList(i, ele)
      }
      else {
        console.log("------------该分类已有商品列表----------")
      }
    }
    /********* 结束 *********/

    //
    this.bottomShowDeal()
    //
    var that = this
    setTimeout(function () {
      that.setData({
        goodsScrollViewToView: 'item0',
      })
    }, 200)
    setTimeout(function () {
      that.setData({
        coverScrollViewShow: false
      })
    }, 500)
  },

  /*
    hide为布尔值
  */
  bottomShowDeal() {
    if (this.findNextCategory()) {
      this.setData({
        hideBottomLoadNext: false,
      })
    }
    else {
      this.setData({
        hideBottomLoadNext: true,
      })
    }
  },

  bindSwiperChange: function (event) {
    var current = event.detail.current
    var source = event.detail.source
    console.log("bindChange: current= " + current + ";  source= " + source)
    if (source == "touch") {
      touchChange = true
    }
  },

  bindSwiperAnimationFinish: function (event) {
    var current = event.detail.current
    var source = event.detail.source
    console.log("bindAnimationFinish: current= " + current + ";  source= " + source)
    if (touchChange) {
      this.setData({
        coverScrollViewItemList: this.data.swiperCategoryArray[current].goodsList
      })
      this.setData({
        coverScrollViewShow: true
      })


      //
      this.setData({
        selectedLevel1Index: this.data.swiperCategoryArray[current].level1Index,
        selectedLevel2Index: this.data.swiperCategoryArray[current].level2Index,
      })
      this.fillSwiperCategoryArray()
      this.setData({
        level1ScrollViewToView: 'item' + this.data.selectedLevel1Index,
        level2ScrollViewToView: 'item' + this.data.selectedLevel2Index,
      })
      wx.vibrateShort()


      touchChange = false
    }
  },


  /*
    模拟请求商品数据
  */
  requestGoodsList(index, ele) {
    var that = this
    setTimeout(function() {
      //模拟服务器返回的商品数据
      var goodsArr = []
      for (var g = 0; g < 20; g++) {
        var goodsItem = {
          id: 'level1_' + ele.level1Index + '_goods_' + g,
          name: '一级' + ele.level1Index + ' - 二级' + ele.level2Index + ' - ' + '商品' + g,
        }
        goodsArr.push(goodsItem)
      }
      var parPath = 'swiperCategoryArray[' + index + '].goodsList'   //将商品列表赋给swiperCategoryArray的项，其实也会自动赋值给categroyTree，因为swiperCategoryArray的项引用的是categroyTree的分类，引用的话在内存中地址是一样的
      that.setData({
        [parPath]: goodsArr
      })
      console.log(that.data.swiperCategoryArray)
    }, 900)
  },

  requestGoodsList(index, swiperCategory) {
    var level1Index = swiperCategory.level1Index
    var level2Index = swiperCategory.level2Index
    var that = this
    setTimeout(function () {
      //模拟服务器返回的商品数据
      var goodsArr = []
      for (var g = 0; g < 20; g++) {
        var goodsItem = {
          id: 'level1_' + level1Index+ '_goods_' + g,
          name: '一级' + level1Index + ' - 二级' + level2Index + ' - ' + '商品' + g,
        }
        goodsArr.push(goodsItem)
      }

      if (that.swiperArrayContainCategory(index, swiperCategory)) {
        var parPath_goodsList = 'swiperCategoryArray[' + index + '].goodsList'   //将商品列表赋给swiperCategoryArray的项，其实也会自动赋值给categroyTree，因为swiperCategoryArray的项引用的是categroyTree的分类，引用的话在内存中地址是一样的
        var parPath_page = 'swiperCategoryArray[' + index + '].page'
        var parPath_last = 'swiperCategoryArray[' + index + '].last'
        that.setData({
          [parPath_goodsList]: goodsArr,
          [parPath_page]: swiperCategory.page ? swiperCategory.page : 1,
          [parPath_last]: true
        })
      }
      else {
        var parPath_goodsList
        var parPath_page
        var parPath_last
        if (that.data.categoryTree.children) {
          parPath_goodsList = 'categoryTree[' + level1Index + '].children[' + level2Index + "].goodsList"
          parPath_page = 'categoryTree[' + level1Index + '].children[' + level2Index + "].page"
          parPath_last = 'categoryTree[' + level1Index + '].children[' + level2Index + "].last"
        }
        else {
          parPath_goodsList = 'categoryTree[' + level1Index + "].goodsList"
          parPath_page = 'categoryTree[' + level1Index + "].page"
          parPath_last = 'categoryTree[' + level1Index + "].last"
        }

        that.setData({
          [parPath_goodsList]: goodsArr,
          [parPath_page]: swiperCategory.page ? swiperCategory.page : 1,
          [parPath_last]: true
        })
      }
    }, 1000)
  },

  swiperArrayContainCategory(index, ele) {
    for (var i=0; i<this.data.swiperCategoryArray.length; i++) {
      var categoryEle = this.data.swiperCategoryArray[i]
      if (ele.id==categoryEle.id && i==index) {
        return true
      }
    }

    return false
  },
})